// 封装 axios 实例
import axios from "axios";
import store from "@/store";
import router from "@/router";
import { Notification } from "element-ui";
const instance = axios.create({
  baseURL: "/api", // 设置基础 URL
  timeout: 5000, // 设置请求超时时间
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么，比如添加 token
    let token = store.state.token;
    // store.commit("removeToken");
    config.headers.Authorization = token;
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
    // console.log(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 对响应数据做些什么
    return response.data;
  },
  (error) => {
    // 对响应错误做些什么;
    if (error.response.status == 401) {
      Notification({
        title: "失败",
        message: "身份校验失败",
        type: "warning",
      });
    } else {
      Notification({
        title: "失败",
        message: "服务器异常",
        type: "warning",
      });
    }
    console.log(router.currentRoute.path);
    if (router.currentRoute.path !== "/login") {
      // router.push("/login");
    }
    return Promise.reject(error);
    // console.log(error);
  }
);

export default instance;
